package com.tjetc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.Result;
import com.tjetc.domain.Medicine;
import com.tjetc.service.MedicineService;
import com.tjetc.service.impl.MedicineServiceImpl;
import com.tjetc.utils.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

@WebServlet("/medicine/*")
@MultipartConfig(location = "D:\\yiyuanphoto")
public class MedicineServlet extends HttpServlet {
    private MedicineService medicineService=new MedicineServiceImpl();
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String curPage = request.getParameter("curPage");
        String ps = request.getParameter("pageSize");
        name=name==null?"":name;

        //接受请求参数
        //空处理:赋值给当前页码
        int currentPage = curPage == null ? 1:Integer.valueOf(curPage);
        //每页显示的条数
        int pageSize = ps == null ? 5 : Integer.parseInt(ps);
        //总记录数
        int count =medicineService.getCount(name);
        PageInfo<Medicine> pageInfo = new PageInfo<>(currentPage, count, pageSize);
        List<Medicine> list=medicineService.list(name,pageInfo);
        pageInfo.setList(list);
        new ObjectMapper().writeValue(response.getOutputStream(),pageInfo);
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        int cid= Integer.parseInt(request.getParameter("cid"));
        String unit=request.getParameter("unit");
        int restamount= Integer.parseInt(request.getParameter("restamount"));
        int warnamount= Integer.parseInt(request.getParameter("warnamount"));
        double price= Double.parseDouble(request.getParameter("price"));
        String address=request.getParameter("address");
        String remarks=request.getParameter("remarks");
        Medicine medicine=new Medicine();
        medicine.setName(name);
        medicine.setCid(cid);
        medicine.setUnit(unit);
        medicine.setRestamount(restamount);
        medicine.setWarnamount(warnamount);
        medicine.setPrice(price);
        medicine.setAddress(address);
        medicine.setRemarks(remarks);
        List<String> photopaths=new ArrayList<>();
        //接收多张图片
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            if (part.getName().equals("photo")){
                String submittedFileName = part.getSubmittedFileName();
                String filename = UUID.randomUUID().toString()+submittedFileName.substring(submittedFileName.lastIndexOf("."));
                part.write(filename);
                photopaths.add("upload/"+filename);
            }
        }
        Medicine medicine1=medicineService.findByName(name);
        if (medicine1!=null){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("添加失败，该药品已存在，如需添加数量请在下方列表修改"));
        }else{
            boolean b=medicineService.add(medicine,photopaths);
            if (b){
                new ObjectMapper().writeValue(response.getOutputStream(), Result.success("添加成功"));
            }
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("添加失败，出异常喽！"));
        }

    }


    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        int cid= Integer.parseInt(request.getParameter("cid"));
        String unit=request.getParameter("unit");
        int restamount= Integer.parseInt(request.getParameter("restamount"));
        int warnamount= Integer.parseInt(request.getParameter("warnamount"));
        double price= Double.parseDouble(request.getParameter("price"));
        String address=request.getParameter("address");
        String remarks=request.getParameter("remarks");
        String paths=request.getParameter("paths");
        System.out.println("paths = " + paths);
        //创建存储上传图片路径的集合
        List<String> photopaths=new ArrayList<>();
        //接收多张图片
        Collection<Part> parts = request.getParts();

        for (Part part : parts) {
            if (part.getName().equals("photo")){
                String submittedFileName = part.getSubmittedFileName();
                System.out.println("submittedFileName = " + submittedFileName);
                String filename = UUID.randomUUID().toString()+submittedFileName.substring(submittedFileName.lastIndexOf("."));
                part.write(filename);
                photopaths.add("upload/"+filename);
            }
        }
        //创建medicine
        Medicine medicine=new Medicine();
        medicine.setId(id);
        medicine.setName(name);
        medicine.setCid(cid);
        medicine.setUnit(unit);
        medicine.setRestamount(restamount);
        medicine.setWarnamount(warnamount);
        medicine.setPrice(price);
        medicine.setAddress(address);
        medicine.setRemarks(remarks);
        boolean b=medicineService.update(medicine,photopaths,paths);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败，出异常喽！"));
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       int id= Integer.parseInt(request.getParameter("id"));
       boolean b=medicineService.del(id);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("删除成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("删除失败，出异常喽！"));
    }

    protected void listAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Medicine> medicines = medicineService.listAll();
        new ObjectMapper().writeValue(response.getOutputStream(), medicines);
    }

    protected void queryByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        Medicine medicine = medicineService.findByName(name);
        new ObjectMapper().writeValue(response.getOutputStream(), medicine);
    }
}
